package com.itmake.sample.tenant.mycat;

import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;

import java.sql.Connection;
import java.util.Objects;
import java.util.Properties;

/**
 * 租户拦截器，根据每次请求的二级域名获取租户 ID
 *
 * @author Amjacks
 * @since 2021/04/30
 */
@Intercepts(value = {
        @Signature(type = StatementHandler.class,
                method = "prepare",
                args = {Connection.class, Integer.class})
})
public class TenantInterceptor implements Interceptor {

    private static final String MYCAT_PREFIX = "/*!mycat:datanode=";
    private static final String MYCAT_SUFFIX = "*/";

    /**
     * 拦截sql，附加前缀
     */
    public Object intercept(Invocation invocation) throws Throwable {
        StatementHandler target = (StatementHandler)invocation.getTarget();
        // 获取执行的sql
        String sql = target.getBoundSql().getSql();

        // 租户前缀
        StringBuilder sb = new StringBuilder();
        if (Objects.nonNull(TenantService.getTenantId())) {
            sb.append(MYCAT_PREFIX);
            sb.append(TenantService.getTenantId());
            sb.append(MYCAT_SUFFIX);
        }
        sb.append(sql);
        // 覆盖sql
        MetaObject metaObject = SystemMetaObject.forObject(target);
        metaObject.setValue("boundSql.sql", sb.toString());
        // 返回执行后的返回值
        return invocation.proceed();
    }

    /**
     * 插件
     */
    public Object plugin(Object target) {
        Object wrap = Plugin.wrap(target, this);
        // 返回为当前target创建的动态代理
        return wrap;
    }

    /**
     * 将插件注册时的property属性设置进来
     */
    public void setProperties(Properties properties) {}
}
